// import axios from "axios";

import axios from 'axios'
import Message from './onlyMessage'
import router from '../router/index'
import OnlyDialog from './OnlyDialog'
import {httpConfig} from './config'
// 创建一个axios的实例
const service = axios.create({
   
  // 基础路径: 需要根据当前的运行环境来判断
  baseURL: httpConfig.baseURL,
  // 超时时间
  timeout: httpConfig.timeout
})


// 请求拦截: 
service.interceptors.request.use((config) => {
if(localStorage.getItem('data')){
    let token = JSON.parse(localStorage.getItem('data')).token
    if (token) {
        // 需要在请求头当中添加token
        config.headers['Authorization'] = token
        config.headers['token'] = token 
      }
}
  
  
  return config
}, err => {
  return Promise.reject(err)
})


// 响应拦截:
service.interceptors.response.use((res) => {
  if(res.data.code=='500'){
    Message.error(res.data.msg)
    return Promise.reject(res)
  }
  if (res.data.code === 400) {
    Message.error('参数错误')
    return Promise.reject(res)
  }
 
  if (res.data.code === 401) {
    if(localStorage.getItem('data')){
      OnlyDialog.show();  
  }else{
    router.push({name:'Login'})
  }

  return Promise.reject(res)
  }
  if (res.data.code === 403) {
    Message.error('没有权限')
    return Promise.reject(res)
  }
  if (res.data.code === 404) {
    Message.error('接口路径错误')
    return Promise.reject(res)
  }
  if (res.data.code === 503) {
    Message.error('服务器在维护')
    return Promise.reject(res)
  }
  return res.data
}, err => {
    Message.error('请求超时，请重试')
  return Promise.reject(err)
})

  export default service


